package com.sunshuo.springsecuritydemo.access;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName DynamicAccessDecisionManager
 * @Description 决策管理器
 * @Author sunshuo
 */
@Component
public class DynamicAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if (collection.isEmpty()) {
            return;
        }
        // 当前用户拥有的访问权限集合
        List<String> authPoints = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        // 决策策略~
        for (ConfigAttribute roleConfigAttribute : collection) {
            String needRoleName = roleConfigAttribute.getAttribute();
            // 通过和当前用户拥有的角色进行比对
            if (authPoints.contains("ROLE_" + needRoleName)) {
                return;
            }
        }
        // 用户没有访问该资源的角色，抛异常
        throw new AccessDeniedException("无权限访问该资源~");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
